package com.stars.controller;

import com.stars.common.MyDateUtils;
import com.stars.common.ObjectCopyUtils;
import com.stars.common.base.BaseConstant;
import com.stars.common.base.command.BaseAppCommand;
import com.stars.common.base.dto.BaseAppDto;
import com.stars.common.base.dto.BaseCompanyDto;
import com.stars.common.base.dto.BaseOrgDto;
import com.stars.common.base.entity.BaseAppEntity;
import com.stars.common.base.entity.BaseCompanyEntity;
import com.stars.common.base.entity.BaseEntity;
import com.stars.common.base.entity.BaseOrgEntity;
import com.stars.common.maps.JsonUtils;
import com.stars.controller.advice.CommonExceptionHandler;
import com.stars.dao.mapper.system.SystemUserMapper;
import com.stars.entity.dto.pas.ChartPurchaseDTO;
import com.stars.entity.dto.sys.SystemUserAppOrgDTO;
import com.stars.entity.sys.SystemUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @author :dj
 * @version : 1.0.0
 * @description
 * @Date 2019-09-27 12:01
 * @note
 */
public class BaseController extends CommonExceptionHandler {

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private SystemUserMapper systemUserMapper;
    /**
     * 获取用户信息
     * @param request
     * @return
     * @throws Exception
     */
    public SystemUserAppOrgDTO getUserInfo(HttpServletRequest request) throws Exception {
        String accessToken = request.getHeader(BaseConstant.ACCESS_TOKEN);
        String redisUserId = redisTemplate.opsForValue().get(accessToken);
        SystemUserAppOrgDTO systemUser = JsonUtils.jsonToPojo(redisTemplate.opsForValue().get(redisUserId+BaseConstant.ACCESS_TOKEN),SystemUserAppOrgDTO.class);
        return systemUser;
    }
    public SystemUser getCurrentUser(HttpServletRequest request) throws Exception {
        String sToken = request.getHeader(BaseConstant.ACCESS_TOKEN);
        String sUserId = redisTemplate.opsForValue().get(sToken);
        SystemUser systemUser = systemUserMapper.selectByPrimaryKey(sUserId);
        return systemUser;
    }
    /**
     * 使用command
     * @param command
     * @param request
     * @return
     * @throws Exception
     */
    public BaseAppCommand addByCommand(BaseAppCommand command,HttpServletRequest request) throws Exception{
        SystemUserAppOrgDTO userInfo = getUserInfo(request);
        if(null != userInfo){
            ObjectCopyUtils.copyPropertiesIf(userInfo,command, BaseConstant.EXCLUDES);
            command.setCreateId(userInfo.getId());
            command.setCreateName(userInfo.getUserRealName());
        }
        return command;
    }

    /**
     * 更新用户系统组织信息
     * @param command
     * @param request
     * @return
     * @throws Exception
     */
    public BaseAppCommand updateByCommand(BaseAppCommand command,HttpServletRequest request) throws Exception{
        SystemUserAppOrgDTO userInfo = getUserInfo(request);
        if(null != userInfo){
            command.setLastUpdateId(userInfo.getId());
            command.setLastUpdateName(userInfo.getUserRealName());
        }

        return command;
    }
    public void setAddBase(BaseEntity baseEntity,HttpServletRequest request,SystemUserAppOrgDTO userInfo) throws Exception {
        if(null == userInfo){
            SystemUserAppOrgDTO user = getUserInfo(request);
            if(null != user){
                baseEntity.setCreateId(user.getId());
                baseEntity.setCreateName(user.getUserRealName());
            }
        }else{
            baseEntity.setCreateId(userInfo.getId());
            baseEntity.setCreateName(userInfo.getUserRealName());
        }
        baseEntity.setCreateDate(new Date());
    }

    public void setUpdateBase(BaseEntity baseEntity,HttpServletRequest request) throws Exception {
        SystemUserAppOrgDTO user = getUserInfo(request);
        if(null != user){
            baseEntity.setLastUpdateId(user.getId());
            baseEntity.setLastUpdateName(user.getUserRealName());
        }
        baseEntity.versionAutoAdd();
        baseEntity.setLastUpdateDate(new Date());
    }

    public void setAddCompany(BaseCompanyEntity appEntity, HttpServletRequest request,SystemUserAppOrgDTO userInfo) throws Exception {
        userInfo = setSystemCompany(appEntity, request, userInfo);
        setAddBase(appEntity,request,userInfo);
    }
    public void setAddBaseOrg(BaseOrgEntity appEntity,HttpServletRequest request,SystemUserAppOrgDTO userInfo) throws Exception {
        //设置基本信息
        userInfo = setSystemOrg(appEntity, request, userInfo);
        setAddCompany(appEntity,request,userInfo);
    }
    /**
     * 返回当前用户信息
     * @param request
     * @return
     * @throws Exception
     */
    public BaseAppEntity setAddBaseApp(BaseAppEntity appEntity, HttpServletRequest request) throws Exception {
        SystemUserAppOrgDTO userInfo = setSystemApp(appEntity, request);
        setAddBaseOrg(appEntity,request,userInfo);
        return appEntity;
    }

    public SystemUserAppOrgDTO setSystemCompany(BaseCompanyEntity appEntity, HttpServletRequest request, SystemUserAppOrgDTO userInfo) throws Exception {
        if(null == userInfo){
            userInfo = getUserInfo(request);
        }
        if(null != userInfo){
            ObjectCopyUtils.copyPropertiesIf(userInfo,appEntity,BaseConstant.EXCLUDES);
        }
        return userInfo;
    }
    public SystemUserAppOrgDTO setSystemCompany(BaseCompanyDto baseCompanyDto, HttpServletRequest request) throws Exception {
        SystemUserAppOrgDTO userInfo = getUserInfo(request);
        if(null != userInfo){
            ObjectCopyUtils.copyPropertiesIf(userInfo,baseCompanyDto,BaseConstant.EXCLUDES);
        }
        return userInfo;
    }

    public SystemUserAppOrgDTO setSystemOrg(BaseOrgEntity appEntity, HttpServletRequest request, SystemUserAppOrgDTO userInfo) throws Exception {
        if(null == userInfo){
            userInfo = getUserInfo(request);
        }
        if(null != userInfo){
            ObjectCopyUtils.copyPropertiesIf(userInfo,appEntity,BaseConstant.EXCLUDES);
        }
        return userInfo;
    }
    public SystemUserAppOrgDTO setSystemOrg(BaseOrgDto baseOrgDto, HttpServletRequest request) throws Exception {
        SystemUserAppOrgDTO userInfo = getUserInfo(request);
        if(null != userInfo){
            ObjectCopyUtils.copyPropertiesIf(userInfo,baseOrgDto,BaseConstant.EXCLUDES);
        }
        return userInfo;
    }
    public SystemUserAppOrgDTO setSystemApp(BaseAppEntity appEntity, HttpServletRequest request) throws Exception {
        SystemUserAppOrgDTO userInfo = getUserInfo(request);
        ObjectCopyUtils.copyPropertiesIf(userInfo,appEntity,BaseConstant.EXCLUDES);
        return userInfo;
    }
    public SystemUserAppOrgDTO setSystemAppExcludesUser(BaseAppEntity appEntity, HttpServletRequest request) throws Exception {
        SystemUserAppOrgDTO userInfo = getUserInfo(request);
        ObjectCopyUtils.copyPropertiesIf(userInfo,appEntity,BaseConstant.EXCLUDES_USER);
        return userInfo;
    }
    public SystemUserAppOrgDTO setSystemApp(BaseAppDto baseAppDto, HttpServletRequest request) throws Exception {
        SystemUserAppOrgDTO userInfo = getUserInfo(request);
        ObjectCopyUtils.copyPropertiesIf(userInfo,baseAppDto,BaseConstant.EXCLUDES);
        return userInfo;
    }

    public String addSql(ChartPurchaseDTO dto){
        StringBuilder sqlWhere = new StringBuilder();
        //当天
        if(StringUtils.isNotBlank(dto.getNowDay())){
            String nowDay = MyDateUtils.format(new Date(),MyDateUtils.YYYY_MM_DD_);
            dto.setYearMonthStart(nowDay);
            dto.setYearMonthEnd(nowDay);
        }
        //本月
        if(StringUtils.isNotBlank(dto.getNowMonth())){
            String beginMonth = MyDateUtils.getMonthFirstDay();
            String endMonth = MyDateUtils.getMonthLastDay();
            sqlWhere.append(" AND DATE_FORMAT(t.CREATE_DATE, '%Y-%m-%d') >= '"+ beginMonth+"'");
            sqlWhere.append(" AND DATE_FORMAT(t.CREATE_DATE, '%Y-%m-%d') <= '"+endMonth+"'");
        }
        //年月查询
        if(StringUtils.isNotBlank(dto.getYearMonthStart())){
            Integer currentYear = MyDateUtils.getCurrentYear(dto.getYearMonthStart());
            Integer currentMonth = MyDateUtils.getCurrentMonth(dto.getYearMonthStart());
            String firstDayOfMonth = MyDateUtils.getFirstDayOfMonth(currentYear, currentMonth);
            sqlWhere.append(" AND DATE_FORMAT(t.CREATE_DATE, '%Y-%m-%d') >= '"+firstDayOfMonth+"'");
        }
        if(StringUtils.isNotBlank(dto.getYearMonthEnd())){
            Integer currentYear = MyDateUtils.getCurrentYear(dto.getYearMonthEnd());
            Integer currentMonth = MyDateUtils.getCurrentMonth(dto.getYearMonthEnd());
            String endDayOfMonth = MyDateUtils.getLastDayOfMonth(currentYear, currentMonth);
            sqlWhere.append(" AND DATE_FORMAT(t.CREATE_DATE, '%Y-%m-%d') <= '"+endDayOfMonth+"'");
        }
        //客户。供应商
        if(null != dto.getCustomerId() && dto.getCustomerId().length>0){
            sqlWhere.append(" AND t.CUSTOMER_ID  in ("+toInStr(dto.getCustomerId())+")");
        }
        if(null !=dto.getSupplierId() && dto.getSupplierId().length>0){
            sqlWhere.append(" AND t.SUPPLIER_ID in ("+toInStr(dto.getSupplierId())+")");
        }
        if(StringUtils.isNotBlank(dto.getOrderStatus())){
            sqlWhere.append(" AND t.ORDER_STATUS ='"+dto.getOrderStatus()+"'");
        }
        if(StringUtils.isNotBlank(dto.getYears())){
            Integer years = Integer.parseInt(dto.getYears());
            sqlWhere.append(" AND DATE_FORMAT(t.CREATE_DATE, '%Y-%m-%d') >= '"+ MyDateUtils.getYearFirst(years)+"'");
            sqlWhere.append(" AND DATE_FORMAT(t.CREATE_DATE, '%Y-%m-%d') <= '"+MyDateUtils.getYearLast(years)+"'");
        }
        if(StringUtils.isNotBlank(dto.getYears()) && StringUtils.isNotBlank(dto.getMonth())){
            Integer years = Integer.parseInt(dto.getYears());
            Integer month = Integer.parseInt(dto.getMonth());
            sqlWhere.append(" AND DATE_FORMAT(t.CREATE_DATE, '%Y-%m-%d') >= '"+MyDateUtils.getFirstDayOfMonth(years,month)+"'");
            sqlWhere.append(" AND DATE_FORMAT(t.CREATE_DATE, '%Y-%m-%d') <= '"+MyDateUtils.getLastDayOfMonth(years,month)+"'");
        }
        return sqlWhere.toString();
    }
    private  String toInStr(String [] strArray){
        if(null == strArray && strArray.length>0){
            return null;
        }
        StringBuilder sqlWhere = new StringBuilder();
        for (String id : strArray) {
            if(StringUtils.isBlank(id)){
                continue;
            }
            sqlWhere.append(" '"+id+"',");
        }
        String sqlStr =sqlWhere.toString();
        return sqlStr.substring(0,sqlStr.length()-1);
    }

}
